{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "\"\"\"A very simple MNIST classifier.\n",
    "See extensive documentation at\n",
    "https://www.tensorflow.org/get_started/mnist/beginners\n",
    "\"\"\"\n",
    "\n",
    "from __future__ import absolute_import\n",
    "from __future__ import division\n",
    "from __future__ import print_function\n",
    "\n",
    "import argparse\n",
    "import sys\n",
    "\n",
    "from tensorflow.examples.tutorials.mnist import input_data\n",
    "\n",
    "import tensorflow as tf\n",
    "\n",
    "FLAGS = None\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "我们在这里调用系统提供的Mnist数据函数为我们读入数据，如果没有下载的话则进行下载。\n",
    "\n",
    "<font color=#ff0000>**这里将data_dir改为适合你的运行环境的目录**</font>"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Extracting C:/Users/lwz/Desktop/MNIST_data/MNIST_data\\train-images-idx3-ubyte.gz\n",
      "Extracting C:/Users/lwz/Desktop/MNIST_data/MNIST_data\\train-labels-idx1-ubyte.gz\n",
      "Extracting C:/Users/lwz/Desktop/MNIST_data/MNIST_data\\t10k-images-idx3-ubyte.gz\n",
      "Extracting C:/Users/lwz/Desktop/MNIST_data/MNIST_data\\t10k-labels-idx1-ubyte.gz\n"
     ]
    }
   ],
   "source": [
    "# Import data\n",
    "tf.logging.set_verbosity(tf.logging.ERROR)\n",
    "data_dir = 'C:/Users/lwz/Desktop/MNIST_data/MNIST_data'\n",
    "mnist = input_data.read_data_sets(data_dir, one_hot=True)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "一个非常非常简陋的模型"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [],
   "source": [
    "n_input = 784\n",
    "n_hidden1 = 300\n",
    "n_hidden2 = 100\n",
    "n_classes = 10\n",
    "\n",
    "def addconnect(inputs, in_size, out_size, activation_function = None):\n",
    "    W = tf.Variable(tf.truncated_normal([in_size, out_size], stddev = 0.01))\n",
    "    b = tf.Variable(tf.zeros([1, out_size]))\n",
    "    logits = tf.matmul(inputs, W) + b\n",
    "    if activation_function is None:\n",
    "        return logits\n",
    "    else:\n",
    "        return activation_function(logits)\n",
    "\n",
    "# Create the model\n",
    "# x = tf.placeholder(tf.float32, [None, n_input])\n",
    "# W = tf.Variable(tf.zeros([784, 10]))\n",
    "# b = tf.Variable(tf.zeros([10]))\n",
    "# y = tf.matmul(x, W) + b"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "定义我们的ground truth 占位符"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Define loss and optimizer\n",
    "x = tf.placeholder(tf.float32, [None, n_input])\n",
    "y_ = tf.placeholder(tf.float32, [None, 10])\n",
    "\n",
    "#layer1 = addconnect(x, n_input, n_hidden1, tf.nn.relu)\n",
    "layer1 = addconnect(x, n_input, n_hidden1, tf.nn.relu)\n",
    "layer2 = addconnect(layer1, n_hidden1, n_hidden2, tf.nn.relu)\n",
    "y = addconnect(layer2, n_hidden2, n_classes)\n",
    "#y = addconnect(x, n_input, n_classes)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "接下来我们计算交叉熵，注意这里不要使用注释中的手动计算方式，而是使用系统函数。\n",
    "另一个注意点就是，softmax_cross_entropy_with_logits的logits参数是**未经激活的wx+b**"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [],
   "source": [
    "# The raw formulation of cross-entropy,\n",
    "#\n",
    "#   tf.reduce_mean(-tf.reduce_sum(y_ * tf.log(tf.nn.softmax(y)),\n",
    "#                                 reduction_indices=[1]))\n",
    "#\n",
    "# can be numerically unstable.\n",
    "#\n",
    "# So here we use tf.nn.softmax_cross_entropy_with_logits on the raw\n",
    "# outputs of 'y', and then average across the batch.\n",
    "cross_entropy = tf.reduce_mean(\n",
    "    tf.nn.softmax_cross_entropy_with_logits_v2(labels=y_, logits=y))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "生成一个训练step"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [],
   "source": [
    "learning_rate = 0.3\n",
    "train_step = tf.train.GradientDescentOptimizer(learning_rate = learning_rate).minimize(cross_entropy)\n",
    "#train_step = tf.train.AdamOptimizer(learning_rate = learning_rate).minimize(cross_entropy)\n",
    "\n",
    "sess = tf.Session()\n",
    "init_op = tf.global_variables_initializer()\n",
    "sess.run(init_op)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "在这里我们仍然调用系统提供的读取数据，为我们取得一个batch。\n",
    "然后我们运行3k个step(5 epochs)，对权重进行优化。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "steps:0 accuracy:0.113500\n",
      "steps:100 accuracy:0.293200\n",
      "steps:200 accuracy:0.802800\n",
      "steps:300 accuracy:0.895900\n",
      "steps:400 accuracy:0.908300\n",
      "steps:500 accuracy:0.934800\n",
      "steps:600 accuracy:0.944200\n",
      "steps:700 accuracy:0.948400\n",
      "steps:800 accuracy:0.897500\n",
      "steps:900 accuracy:0.959700\n",
      "steps:1000 accuracy:0.957200\n",
      "steps:1100 accuracy:0.964100\n",
      "steps:1200 accuracy:0.967600\n",
      "steps:1300 accuracy:0.961700\n",
      "steps:1400 accuracy:0.971200\n",
      "steps:1500 accuracy:0.965800\n",
      "steps:1600 accuracy:0.970900\n",
      "steps:1700 accuracy:0.969800\n",
      "steps:1800 accuracy:0.975800\n",
      "steps:1900 accuracy:0.970500\n",
      "steps:2000 accuracy:0.971400\n",
      "steps:2100 accuracy:0.972300\n",
      "steps:2200 accuracy:0.970500\n",
      "steps:2300 accuracy:0.971800\n",
      "steps:2400 accuracy:0.975500\n",
      "steps:2500 accuracy:0.955800\n",
      "steps:2600 accuracy:0.976900\n",
      "steps:2700 accuracy:0.977200\n",
      "steps:2800 accuracy:0.974500\n",
      "steps:2900 accuracy:0.974200\n"
     ]
    }
   ],
   "source": [
    "# Train\n",
    "for i in range(3000):\n",
    "    batch_xs, batch_ys = mnist.train.next_batch(100)\n",
    "    sess.run(train_step, feed_dict={x: batch_xs, y_: batch_ys})\n",
    "    if i % 100 == 0:\n",
    "        correct_prediction = tf.equal(tf.argmax(y, 1), tf.argmax(y_, 1))\n",
    "        accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))\n",
    "        print(\"steps:%d accuracy:%4f\"%(i, sess.run(accuracy, feed_dict={x: mnist.test.images,\n",
    "                                      y_: mnist.test.labels})))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "验证我们模型在测试数据上的准确率"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "0.9784\n"
     ]
    }
   ],
   "source": [
    "  # Test trained model\n",
    "correct_prediction = tf.equal(tf.argmax(y, 1), tf.argmax(y_, 1))\n",
    "accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))\n",
    "print(sess.run(accuracy, feed_dict={x: mnist.test.images,\n",
    "                                      y_: mnist.test.labels}))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "毫无疑问，这个模型是一个非常简陋，性能也不理想的模型。目前只能达到92%左右的准确率。\n",
    "接下来，希望大家利用现有的知识，将这个模型优化至98%以上的准确率。\n",
    "Hint：\n",
    "- 多隐层\n",
    "- 激活函数\n",
    "- 正则化\n",
    "- 初始化\n",
    "- 摸索一下各个超参数\n",
    "  - 隐层神经元数量\n",
    "  - 学习率\n",
    "  - 正则化惩罚因子\n",
    "  - 最好每隔几个step就对loss、accuracy等等进行一次输出，这样才能有根据地进行调整"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.2"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
